import 'package:e_reception_flutter/singleton/theme_repository/theme_repository.dart';
import 'package:e_reception_flutter/singleton/user_repository/bean/user_response_bean.dart';
import 'package:e_reception_flutter/singleton/user_repository/user_repository.dart';
import 'package:e_reception_flutter/ui/index/even/clear_index_company_info_event.dart';
import 'package:e_reception_flutter/ui/login/login_bean/login_search_organization_bean.dart';
import 'package:e_reception_flutter/utils/router_utils.dart';
import 'package:e_reception_flutter/utils/vg_string_utils.dart';
import 'package:e_reception_flutter/vg_widgets/vg_place_holder_status_widget/vg_place_holder_status_widget.dart';
import 'package:e_reception_flutter/vg_widgets/vg_top_bar_widget/vg_top_bar_widget.dart';
import 'package:flutter/material.dart';
import 'package:vg_base/vg_arch_lib.dart';
import 'package:vg_base/vg_evnet_bus_lib.dart';
import 'package:vg_base/vg_sp_lib.dart';
import 'package:vg_base/vg_string_util_lib.dart';
import 'package:vg_flutter_base_moudle/vg_moudle_widget_lib.dart';

import '../../app_main.dart';
import 'bean/company_switch_list_bean.dart';
import 'company_switch_view_model.dart';
import 'widgets/company_switch_list_item_widget.dart';

/// 企业切换
///
/// @author: zengxiangxi
/// @createTime: 1/23/21 3:46 PM
/// @specialDemand:
class CompanySwitchPage extends StatefulWidget {
  ///路由名称
  static const String ROUTER = "CompanySwitchPage";

  final List<OrgInfoListBean> orgInfoList;

  final bool loginPage;

  final CompanySwitchListBean companySwitchListBean;

  const CompanySwitchPage({Key key, this.orgInfoList, this.loginPage, this.companySwitchListBean}) : super(key: key);

  @override
  _CompanySwitchPageState createState() => _CompanySwitchPageState();

  ///跳转方法
  static Future<dynamic> navigatorPush(BuildContext context,{List<OrgInfoListBean> orgInfoList,bool loginPage,CompanySwitchListBean companySwitchListBean}) {
    return RouterUtils.routeForFutureResult(
      context,
      CompanySwitchPage(
          orgInfoList:orgInfoList,loginPage:loginPage,companySwitchListBean:companySwitchListBean
      ),
      routeName: CompanySwitchPage.ROUTER,
    );
  }
}

class _CompanySwitchPageState extends BaseState<CompanySwitchPage> {
  List<UserComListBean> _companyList;

  String _selectCompanyId;

  CompanySwitchViewModel _viewModel;

  // List<OrgInfoListBean> orgSwitchInfoList;

  @override
  void initState() {
    super.initState();
    _companyList = List<UserComListBean>();
    _viewModel = CompanySwitchViewModel(this);
    //选择需要导入的机构
    // if((widget?.companySwitchListBean?.data?.userComList?.length??0) == 0){
    //   if((widget?.companySwitchListBean?.data?.yqxList?.length??0)!=0){
    //     widget?.companySwitchListBean?.data?.yqxList?.forEach((element) {
    //       UserComListBean userComListBean = UserComListBean();
    //       userComListBean?.companynick = element?.oname;
    //       userComListBean?.isimport = element?.isimport;
    //       userComListBean?.companyid = element?.orgid;
    //       _companyList?.add(userComListBean);
    //     });
    //   }
    // }else{
    //   widget?.companySwitchListBean?.data?.userComList?.forEach((element) {
    //     UserComListBean userComListBean = UserComListBean();
    //     userComListBean?.companynick = element?.companynick;
    //     userComListBean?.companyname = element?.companyname;
    //     userComListBean?.companyid = element?.companyid;
    //     userComListBean?.type = element?.type;
    //     _companyList?.add(userComListBean);
    //   });
    // }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      // backgroundColor: ThemeRepository.getInstance().getCardBgColor_21263C(),
      backgroundColor: Color(0xFF191E31),
      body: _toMainColumnWidget(),
    );
  }

  Widget _toMainColumnWidget() {
    return Column(
      children: <Widget>[
        _toTopBarWidget(),
        Expanded(
          child: VgPlaceHolderStatusWidget(
              emptyStatus: _companyList == null || _companyList.isEmpty,
              child: _toListWidget()),
        )
      ],
    );
  }

  Widget _toTopBarWidget() {
    return VgTopBarWidget(
      isShowBack: true,
      title: "选择切换",
      backgroundColor: ThemeRepository.getInstance().getBgOrSplitColor_191E31(),
    );
  }

  Widget _toListWidget() {
    return ScrollConfiguration(
      behavior: MyBehavior(),
      child: ListView.separated(
          itemCount: _companyList?.length ?? 0,
          physics: ClampingScrollPhysics(),
          padding: const EdgeInsets.all(0),
          keyboardDismissBehavior: ScrollViewKeyboardDismissBehavior.onDrag,
          itemBuilder: (BuildContext context, int index) {
            return CompanySwitchListItemWidget(
                itemBean: _companyList?.elementAt(index),
                selectCompanyId: _selectCompanyId,
                onTap: (UserComListBean itemBean) {
                  String companyId = UserRepository.getInstance().getCompanyId();
                  if(StringUtils.isNotEmpty(companyId) && companyId == itemBean.companyid){
                    print("公司id相同， 不执行切换");
                    return;
                  }
                  if(itemBean?.isimport=="00"){
                    OrgInfoListBean orgBean = OrgInfoListBean();
                    widget?.orgInfoList?.forEach((element) {
                      if(itemBean?.companyid?.contains(element?.orgid)){
                        orgBean = element;
                      }
                    });
                    if(orgBean==null){
                      return;
                    }
                    if(orgBean?.phone==null || orgBean?.phone == ""){
                      orgBean?.phone =  UserRepository?.getInstance()?.getPhone();
                    }
                    //倒入机构信息并登录
                    UserRepository.getInstance()
                        .loginService().companyImportOrgLogin(context,orgBean?.phone??UserRepository?.getInstance()?.getPhone(), "2828",orgBean);
                    // RouterUtils.pop(context);
                  }else{
                    _viewModel?.changeCompanyHttp(context, itemBean?.companyid,widget?.loginPage);
                  }
                  VgEventBus.global.send(new ClearIndexCompanyInfoEvent(false));
                });
          },
          separatorBuilder: (BuildContext context, int index) {
            return Container(
              height: 0.5,
              color: ThemeRepository.getInstance().getBgOrSplitColor_191E31(),
              margin: const EdgeInsets.only(left: 15, right: 1),
            );
          }),
    );
  }

  // @override
  // void didChangeDependencies() {
  //   super.didChangeDependencies();
  //   UserDataBean userDataBean = UserRepository.getInstance().of(context);
  //   if((widget?.companySwitchListBean?.data?.userComList?.length??0) == 0){
  //     if((widget?.companySwitchListBean?.data?.yqxList?.length??0)!=0){
  //       widget?.companySwitchListBean?.data?.yqxList?.forEach((element) {
  //         UserComListBean userComListBean = UserComListBean();
  //         userComListBean?.companynick = element?.oname;
  //         userComListBean?.isimport = element?.isimport;
  //         userComListBean?.companyid = element?.orgid;
  //         _companyList?.add(userComListBean);
  //       });
  //     }
  //   }else{
  //     _selectCompanyId = userDataBean?.companyId;
  //     widget?.companySwitchListBean?.data?.userComList?.forEach((element) {
  //       UserComListBean userComListBean = UserComListBean();
  //       userComListBean?.companynick = element?.companynick;
  //       userComListBean?.companyname = element?.companyname;
  //       userComListBean?.companyid = element?.companyid;
  //       userComListBean?.type = element?.type;
  //       _companyList?.add(userComListBean);
  //     });
  //   }
  //   setState(() { });
  // }

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
    UserDataBean userDataBean = UserRepository.getInstance().of(context);
    if(userDataBean==null){
      if((widget?.orgInfoList?.length??0)!=0){
        widget?.orgInfoList?.forEach((element) {
          UserComListBean userComListBean = UserComListBean();
          userComListBean?.companynick = element?.oname;
          userComListBean?.isimport = element?.isimport;
          userComListBean?.companyid = element?.orgid;
          _companyList?.add(userComListBean);
        });
        // orgSwitchInfoList = widget?.orgInfoList;
      }
    }else{
      _companyList = userDataBean?.companyList;
      _selectCompanyId = userDataBean?.companyId;
      if((widget?.orgInfoList?.length??0)!=0){
        List<String> orgidsList = List<String>();
        List<String> namesList = List<String>();
        _companyList?.forEach((comName) {
          if(comName?.companynick!=null){
            orgidsList?.add(comName?.companyid);

            namesList?.add(comName?.companynick);
          }

        });
        widget?.orgInfoList?.forEach((element) {
          if(element?.isimport=="00"&&!(VgStringUtils?.getSplitStr(orgidsList, symbol: ",")?.contains(element?.orgid))){
            UserComListBean userComListBean = UserComListBean();
            userComListBean?.companynick = element?.oname;
            userComListBean?.isimport = element?.isimport;
            userComListBean?.companyid = element?.orgid;
            _companyList?.add(userComListBean);
          }
        });
        setState(() { });
        // orgSwitchInfoList = widget?.orgInfoList;
      }
    }
  }
}
